package lkx.demo.test2;

/**
 * 数组的扩容与缩容
 *
 * @author kunxianli
 * @date 2024/01/31 17:53
 **/
public class TestArrayChangeSize4 {

    public static void main(String[] args) {

// ***************** 数组的扩容 *****************************************


        int[] arr = new int[]{1,2,3,4,5};
//        int[] newArr = new int[arr.length * 2];
        //或
        int[] newArr = new int[arr.length << 1];
        //将原有数组中的元素复制到新的数组中
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        //将新的数组的地址赋值给原有的数组变量
        arr = newArr;

        System.out.println(arr.length);

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }


        System.out.println();
        // ***************** 数组的缩容*****************************************
        // 需求： 删除指定位置的数据，例如删掉 5 ，让数组变成 {1,2,3,4,6,7}
        int[] arr1={1,2,3,4,5,6,7};

        int deleteIndex = 4;

        //方式1：不新建数组
        for(int i = deleteIndex;i < arr1.length - 1;i++){
            arr1[i] = arr1[i + 1];
        }

        //修改最后元素,设置为默认值
        arr1[arr1.length - 1] = 0;
        //遍历arr数组
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + "\t");
        }

        //  方式二：新建数组

        int[] arr2={1,2,3,4,5,6,7};

        int deleteIndex2 = 4;

        int[] newArr2 = new int[arr2.length - 1];
        for (int i = 0; i < deleteIndex2; i++) {
            newArr2[i] = arr2[i];
        }

        for(int i = deleteIndex2;i < arr2.length - 1;i++){
            newArr2[i] = arr2[i + 1];
        }

        arr2 = newArr2;

        //遍历arr数组
        for (int i = 0; i < arr2.length; i++) {
            System.out.print(arr2[i] + "\t");
        }


    }

}
